package com.cart.services;

import com.cart.pojo.Product;
import com.cart.utils.FileUtil;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class ProductRepositoryImpl implements ProductRepository {

    private List<Product> products = new ArrayList<>();
    private final String PRODUCTS_FILE = "products"; // 商品数据文件

    // 在启动时读取数据
    public ProductRepositoryImpl() throws InvocationTargetException {
        List<Product> loadedProducts = FileUtil.readFromFile(PRODUCTS_FILE, Product.class);
        if (loadedProducts != null) {
            products = loadedProducts;
        }
    }

    @Override
    public List<Product> findAll() {
        return new ArrayList<>(products);
    }

    @Override
    public Product findById(int id) {
        for (Product product : products) {
            if (product.getId() == id) {
                return product;
            }
        }
        return null;
    }

    @Override
    public void save(Product product) {
        products.add(product);
    }

    @Override
    public void update(Product product) {
        Product existingProduct = findById(product.getId());
        if (existingProduct != null) {
            products.set(products.indexOf(existingProduct), product);
        }
    }

    @Override
    public void delete(int id) {
        products.removeIf(product -> product.getId() == id);
    }

    // 程序退出时将商品信息保存到文件
    public void saveToFile() {
        FileUtil.writeToFile(PRODUCTS_FILE, products);
    }
}
